package server.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import util.common.ConfigFileConstants;

/*
 * O papel desta classe é vincular a aplicação à camada de persistência.
 *
 * @author fabianmartins
 *
 */
public class DBUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static final String DATABASE_FILE_NAME = "database.properties";    

    /**
     * Este método inicializa o Hibernate, fornecendo a ele o arquivo de
     * configuração 'resource/hibernate.cfg.xml' que inicializara' a
     * SessionFactory
     *
     * @return
     */
    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.configure("resource/hibernate.cfg.xml");
            configuration.setProperty("hibernate.connection.url", getConnectionUrl());
            configuration.setProperty("hibernate.connection.username", getUsername());
            configuration.setProperty("hibernate.connection.password", getPassword());
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            return configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Erro na inicializacao da SessionFactory" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getCurrentSession() {
        Session session = sessionFactory.getCurrentSession();
        if (!session.isOpen()) {
            session = sessionFactory.openSession();
        }
        return session;
    }
    
    private static String getConnectionUrl(){
        return ConfigFileConstants.getFileConfig(DATABASE_FILE_NAME, "HIBERNATE_CONNECTION_URL");
    }
    
    private static String getUsername(){
        return ConfigFileConstants.getFileConfig(DATABASE_FILE_NAME, "HIBERNATE_USERNAME");
    }
    
    private static String getPassword(){
        return ConfigFileConstants.getFileConfig(DATABASE_FILE_NAME, "HIBERNATE_PASSWORD");
    }

}
